local msg = require "mp.msg"
local utils = require "mp.utils"

local opts = {
    bzip2 = "1",
    screen_subtitles = "s",
    screen_video = "S",
    screen_window = "Ctrl+s"
}(require 'mp.options').read_options(opts, "screenshot_to_farbfeld")

local home = os.getenv("HOME")
local tempFile=home .. "/.cache/mpv_screen_tmp.png"
local screenshotDir=mp.get_property("screenshot-directory")

screenshotDir=mp.command_native({"expand-path", screenshotDir})

if screenshotDir == "" or screenshotDir == nil then
	local popen=io.popen("xdg-user-dir PICTURES")
	local default_dir=popen:read("l")
	popen:close()
	if default_dir == nil then
		default_dir = home
	end
	screenshotDir = utils.join_path(default_dir, "mpv")
	os.execute("mkdir -p " .. screenshotDir)
	msg.log("warn", "No screenshot folder configured! Defaulting to " .. screenshotDir )
end

local function screenshotToFarbfeld(type)
	local error=false
	local filename = string.gsub(string.gsub(mp.get_property("filename"), "'", '"'), "%.%w*$", "") .. " " .. mp.get_property("playback-time") .. ".ff"
	local screenshotName = utils.join_path(screenshotDir, filename)
	mp.commandv("screenshot-to-file", tempFile, type)
	if os.execute("convert " .. tempFile .. " '" .. screenshotName .. "'") > 0 then
		error = true
		msg.log("error", "Could not make screenshot " .. filename)
	end
	if opts.bzip2 == "1" then
		if not (os.execute("bzip2 -f '" .. screenshotName .. "'") > 0) then
			filename = filename .. ".bz2"
		else
			msg.log("error", "Could not compress '" .. filename .. "'")
			error =  true
		end
	end
	if error then
		mp.osd_message("Screenshot Failed", 5)
	else
		mp.osd_message("Screenshot Taken: " .. filename, 5)
	end
	os.remove(tempFile)
end

local function screenshotVideo()
	screenshotToFarbfeld("video")
end

local function screenshotSubtitles()
	screenshotToFarbfeld("subtitles")
end

local function screenshotWindow()
	screenshotToFarbfeld("window")
end

mp.add_key_binding(opts.screen_subtitles, "FFScreenub", screenshotSubtitles)
mp.add_key_binding(opts.screen_video, "FFScreenVid", screenshotVideo)
mp.add_key_binding(opts.screen_win, "FFScreenWin", screenshotWindow)
